package com.kingviker.example.nio;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Random;

public class NioTest13 {
    public static void main(String[] args) throws IOException {
        String inputFile = "NioTest13.text";
        String outputFile = "NioTest13_out.text";
        RandomAccessFile  inputRandomAccessFile = new RandomAccessFile(inputFile,"r");
        RandomAccessFile outputRandomAccessFile = new RandomAccessFile(outputFile, "rw");

        long inputLength = new File(inputFile).length();

        FileChannel inputRandomAccessFileChannel = inputRandomAccessFile.getChannel();
        FileChannel outputRandomAccessFileChannel = outputRandomAccessFile.getChannel();
        MappedByteBuffer inputData = inputRandomAccessFileChannel.map(FileChannel.MapMode.READ_ONLY, 0, inputLength);

//        Charset charset = Charset.forName("utf-8");
        Charset charset = Charset.forName("iso-8859-1");//为什么这个编码格式不会产生中文乱码
        CharsetDecoder charsetDecoder = charset.newDecoder();
        CharsetEncoder charsetEncoder = charset.newEncoder();

        CharBuffer charBuffer = charsetDecoder.decode(inputData);
        ByteBuffer byteBuffer = charsetEncoder.encode(charBuffer);

        outputRandomAccessFileChannel.write(byteBuffer);

        inputRandomAccessFile.close();
        outputRandomAccessFile.close();


    }
}
